package com.yesun.task.pipeline.handler.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yesun.core.util.FileUtils;
import com.yesun.server.mdp.service.client.config.HttpConfig;
import com.yesun.server.mdp.service.client.impl.DefaultClient;
import com.yesun.server.mdp.service.client.impl.http.HttpRequestContext;
import com.yesun.server.mdp.service.client.impl.http.HttpResponseContext;
import com.yesun.task.pipeline.common.Constant;
import com.yesun.task.pipeline.common.StockCode;
import com.yesun.task.pipeline.domain.dto.JobDto;
import com.yesun.task.pipeline.domain.dto.TaskDto;
import com.yesun.task.pipeline.handler.Executor;
import com.yesun.task.pipeline.handler.Handler;
import com.yesun.task.pipeline.handler.Loader;
import com.yesun.task.pipeline.worker.ParallelWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.BlockingQueue;

//财务数据Handler
//数据来源：http://basic.10jqka.com.cn/mobile/ajaxnew/finance/300624/maintablen/all/
@Slf4j
public class FinanceHandler extends Handler {

    static DefaultClient client = new DefaultClient();
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyyMMdd");
    static String TODAY = shortSdf.format(Calendar.getInstance().getTime());

    public FinanceHandler(JobDto jobDto) {
        super(jobDto);
    }

    @Override
    public Loader getLoader() {
        //实例化
        return new Loader() {
            @Override
            public void load(BlockingQueue queue) {
                log.info("加载财务数据采集子任务...");
                //实现资金流入子任务，插入到队列
                String[] arr = StockCode.STOCK_CODE.split(",");
                for(String code : arr) {
                    //update
                    long currentTime = System.currentTimeMillis();

                    String url = "http://basic.10jqka.com.cn/mobile/ajaxnew/finance/"+ code +"/maintablen/all/";;
                    TaskDto taskDto = new TaskDto();
                    taskDto.setJobName(jobDto.getJobName());
                    taskDto.setName(code + "财务数据采集任务");
                    taskDto.setTag(Constant.JOB_TAG_FINANCE);

                    Map<String,String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("code", code);
                    map.put("saveTo", "/df_finance/"+ shortSdf.format(new Date()) +"/"+code+".csv");//暂时只支持保存到磁盘
                    taskDto.setMap(map);

                    //加入MAP_TASK
                    ParallelWorker.MAP_TASK.put(taskDto.getName(), taskDto.getJobName());

                    queue.offer(taskDto);
                    log.info("添加子任务：" + taskDto.getName());
                }
            }
        };
    }

    @Override
    public Executor getExecutor() {
        return new Executor() {
            @Override
            public void execute(TaskDto taskDto) {
                //执行task的采集
                log.info("execute：" + taskDto.getName());
                HttpConfig config = new HttpConfig(taskDto.getMap().get("url"), HttpConfig.HTTP_METHOD_GET);
                config.setEnctype("");
                config.setEncoding("UTF-8");
                HttpRequestContext request = new HttpRequestContext(config);
                try {
                    HttpResponseContext response = (HttpResponseContext) client.execute(request);
                    String content = response.getContentAsString("UTF-8");
                    StringBuffer sbResult = new StringBuffer("股票代码,股票名称,报告期,关键指标,营业总收入,净利润,扣非净利润,每股指标,每股收益,每股净资产,每股资本公积金,每股未分配利润,每股经营现金流,盈利能力,净资产收益率,净资产收益率-摊薄,销售毛利率,存货周转率,资本结构,资产负债率,成长能力,净利润同比增长率,营业收入同比增长率,\n");
                    JSONObject obj = JSONObject.parseObject(content);
                    for(int i=0; i<obj.getJSONArray("finance").size(); i++) {
                        JSONObject unit = (JSONObject)obj.getJSONArray("finance").get(i);
                        Iterator iter = unit.entrySet().iterator();
                        StringBuffer sb = new StringBuffer(taskDto.getMap().get("code") + ",");
                        while (iter.hasNext()) {
                            Map.Entry entry = (Map.Entry)iter.next();
                            if(entry.getKey().equals("list")) {
                                //读取list
                                JSONArray list = (JSONArray)entry.getValue();
                                for(int j=0; j<list.size(); j++) {
                                    JSONObject o = (JSONObject)list.get(j);
                                    //单位
                                    if(o.getString("unit").equals("万")) {
                                        sb.append((Float.parseFloat(o.getString("value")) * 10000) + ",");
                                    } else if(o.getString("unit").equals("亿")) {
                                        sb.append((Float.parseFloat(o.getString("value")) * 10000 * 10000) + ",");
                                    } else if(o.getString("unit").equals("万亿")) {
                                        sb.append((Float.parseFloat(o.getString("value")) * 10000 * 10000 * 10000) + ",");
                                    } else if(o.getString("unit").equals("%")) {
                                        sb.append(o.getString("value") + "%,");
                                    }  else if(o.getString("unit").equals("次")) {
                                        sb.append(o.getString("value") + "次,");
                                    } else {
                                        sb.append(o.getString("value") + ",");
                                    }
                                }
                            } else {
                                sb.append(entry.getValue() + ",");
                            }
                        }
                        sbResult.append(sb.toString()+"\n");
                    }
                    //log.info(sbResult.toString());
                    //save to
                    FileUtils.saveCsv(Constant.BASE_PATH + taskDto.getMap().get("saveTo"), sbResult.toString(), "UTF-8");
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
